package com.deyuanyun.pic.settings.service.org.impl;

import com.deyuanyun.pic.common.tool.Globals;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.settings.controller.dto.UserSessionVO;
import com.deyuanyun.pic.settings.controller.dto.org.CompanyDTO;
import com.deyuanyun.pic.settings.controller.dto.org.CompanyLogoVO;
import com.deyuanyun.pic.settings.controller.dto.org.CompanyVO;
import com.deyuanyun.pic.settings.controller.dto.org.DeptVO;
import com.deyuanyun.pic.settings.controller.dto.prvlg.UserVO;
import com.deyuanyun.pic.settings.domain.base.Attachment;
import com.deyuanyun.pic.settings.domain.base.AttachmentExample;
import com.deyuanyun.pic.settings.domain.org.Company;
import com.deyuanyun.pic.settings.domain.org.OrgInfo;
import com.deyuanyun.pic.settings.domain.prvlg.CustomUser;
import com.deyuanyun.pic.settings.domain.util.DomainInitUtil;
import com.deyuanyun.pic.settings.mapper.base.AttachmentMapper;
import com.deyuanyun.pic.settings.mapper.org.CompanyMapper;
import com.deyuanyun.pic.settings.mapper.org.DeptMapper;
import com.deyuanyun.pic.settings.mapper.org.OrgInfoMapper;
import com.deyuanyun.pic.settings.service.base.AttachmentService;
import com.deyuanyun.pic.settings.service.org.CompanyService;
import com.deyuanyun.pic.settings.service.prvlg.UserService;
import com.deyuanyun.pic.settings.support.cache.SessionCacheSupport;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CompanyServiceImpl implements CompanyService {

	@Resource
	CompanyMapper companyMapper;
	
	@Resource
	OrgInfoMapper orgInfoMapper;
	
	@Resource
	DeptMapper deptMapper;

    @Resource
    private AttachmentService attachmentService;

    @Resource
    private AttachmentMapper attachmentMapper;

    private static final String COMPANY_LOGO_TYPE = "companyLogo";

    @Resource
    private UserService userService;
	
    /**
     * 逻辑删除附件信息
     * @param businessId
     */
    private void updateAttachmentDelete(String businessId) {
        AttachmentExample attachmentExample = new AttachmentExample();
        attachmentExample.createCriteria().andDeletedEqualTo((short) 0).andBusinessIdEqualTo(businessId);
        List<Attachment> atts =attachmentMapper.selectByExample(attachmentExample);
        if(atts != null && !atts.isEmpty()) {
            Attachment atta;
            for (int i = 0, len = atts.size(); i < len; i++) {
                atta = atts.get(i);
                atta.setDeleted((short) 1);
                DomainInitUtil.initUpdateDomain(atta);
                attachmentMapper.updateByPrimaryKeySelective(atta);
            }
        }
    }

    /**
     * 更新公司启用状态
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-11-11
     */
	@Override
    @CacheEvict(value = "tempStoreData", key = "#root.targetClass.toString() + 'queryCacheAll'")
	public int updateState(HashMap param) {
		return companyMapper.updateState(param);
	}

	private boolean getParent(String path,String id,List<CompanyDTO> data){
		if(id == null) {
			return true;
		}
		for(CompanyDTO c : data) {
			String cid = c.getId();
			String cpid=c.getParentId();
			if(id.equals(cid)){
				if(!StringUtils.isEmpty(cpid)) {
					if(path.indexOf(cpid) >= 0) {
						return false;
					}
					return getParent(cpid + "->" + path, cpid, data);
				}else{
					return true;
				}
				
			}
		}
		return false;
	}

    /**
     * 删除公司信息
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-11-11
     */
    @Override
    @CacheEvict(value = "tempStoreData", key = "#root.targetClass.toString() + 'queryCacheAll'")
    public int deleteInfo(List<String> idList) {
        DeptVO deptVO = new DeptVO();
        deptVO.setCompanyIdList(idList);
        List page = deptMapper.queryAll(deptVO);
        Asserts.assertTrue(page.isEmpty(), "公司不能被删除,下面存在部门");
        CompanyVO companyVO = new CompanyVO();
        companyVO.setParentIdList(idList);
        page = companyMapper.queryAll(companyVO);
        Asserts.assertTrue(page.isEmpty(), "公司不能被删除，还有下级公司");

        HashMap search=new HashMap();
        search.put("idList", idList);
        int n = companyMapper.deleteByPrimaryKey(search); //删除公司信息
        for(int i = 0, len = idList.size(); i < len; i++) {
            String id = idList.get(i);
            if(StringUtils.isNotEmpty(id)) {
                orgInfoMapper.deleteByPrimaryKey(id);
                updateAttachmentDelete(id); //逻辑删除公司logo
            }
        }
        return n;
    }

    /**
     * 保存公司信息
     * @param companyVO
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-11-09
     */
    @Override
    @CacheEvict(value = "tempStoreData", key = "#root.targetClass.toString() + 'queryCacheAll'")
    public void saveInfo(CompanyVO companyVO) {
        companyVO.setState((short) 0);
        Company info = new Company();
        BeanUtils.copyProperties(companyVO, info);
        String shortName = info.getShortName();
        Asserts.assertTrue(!StringUtils.isEmpty(shortName), "公司名称不能为空");
        info.setName(shortName);

        String parentId = info.getParentId();
        String attachmentId = companyVO.getAttachmentId();

        CompanyVO vo = new CompanyVO();
        vo.setShortName(shortName);
        List<CompanyDTO> page = companyMapper.queryAll(vo);
        Asserts.assertTrue(page.isEmpty(), "系统已经存在相同的公司名称");

        boolean hasAttachmentId = StringUtils.isNotEmpty(attachmentId);
        Asserts.assertTrue(!(StringUtils.isEmpty(parentId) && !hasAttachmentId), "第一级的公司必须上传公司logo");

        DomainInitUtil.initCreateDomain(info);
        String id = info.getId();

        companyMapper.insertSelective(info);
        OrgInfo record=new OrgInfo();
        BeanUtils.copyProperties(info, record);
        record.setType("0");
        record.setOrgId(id);
        record.setIdPath(id);
        if(StringUtils.isNotEmpty(parentId)){
            Map map = orgInfoMapper.findOrg(parentId);
            record.setIdPath((String)map.get("ID_PATH") + "#" + record.getIdPath());
        }
        orgInfoMapper.insertSelective(record);

        if(hasAttachmentId) {//有附件的时候
            Attachment attachment = attachmentMapper.selectByPrimaryKey(attachmentId);
            if(attachment != null) {
                String businessId = attachment.getBusinessId();
                if(StringUtils.isNotEmpty(businessId) && !id.equals(businessId)) { //附件业务id不为空并且不等于公司id，拷贝一份记录
                    DomainInitUtil.initCreateDomain(attachment);
                    attachment.setBusinessId(id); //重新赋值业务关联id为当前公司id
                    attachmentService.insertSelective(attachment); //插入当前使用的公司logo
                }
                if(StringUtils.isEmpty(businessId)) {
                    DomainInitUtil.initUpdateDomain(attachment, "关联公司logo");
                    attachment.setBusinessId(id); //重新赋值业务关联id为当前公司id
                    attachmentMapper.updateByPrimaryKeySelective(attachment); //更新附件表信息
                }
            }
        } else { //没得附件的时候使用循环查找上级公司logo
            Attachment attachment = null;
            while(true) {
                if(StringUtils.isNotEmpty(parentId)) {
                    info = companyMapper.selectByPrimaryKey(parentId);
                }
                if(info != null) {
                    parentId = info.getParentId();
                    attachment = attachmentService.queryAttachmentByCustomOne(info.getId(), COMPANY_LOGO_TYPE);
                }
                if(info == null || attachment != null) {
                    break;
                }
            }
            if(info != null && attachment != null) {
                DomainInitUtil.initCreateDomain(attachment, "取上级公司logo");
                attachment.setBusinessId(id); //重新赋值业务关联id为当前公司id
                attachmentMapper.insertSelective(attachment);
            }
        }
    }


    /**
     * 更新公司信息
     * @param companyVO
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-11-09
     */
	@Override
    @CacheEvict(value = "tempStoreData", key = "#root.targetClass.toString() + 'queryCacheAll'")
	public void updateInfo(CompanyVO companyVO) {
        Company info = new Company();
        BeanUtils.copyProperties(companyVO, info);
        String id = info.getId();
        String parentId = info.getParentId();
        Asserts.assertTrue(!id.equals(parentId), "上级公司不能是自己");

        String shortName = info.getShortName();
        Asserts.assertTrue(!StringUtils.isEmpty(shortName), "公司名称不能为空");
        info.setName(shortName);
        CompanyVO vo = new CompanyVO();
        vo.setShortName(shortName);
        vo.setId(id);
        List<CompanyDTO> companyDTOs = companyMapper.queryAll(vo);
        Asserts.assertTrue(companyDTOs.isEmpty(), "系统已经存在相同的公司名称");

        if(StringUtils.isNotEmpty(parentId)) {
            Asserts.assertTrue(getParent(id, parentId, companyMapper.queryAll(new CompanyVO())), "上级公司错误，不能为自己的下级公司");
        }

        String attachmentId = companyVO.getAttachmentId();
        boolean hasAttachmentId = StringUtils.isNotEmpty(attachmentId);
        Asserts.assertTrue(!(StringUtils.isEmpty(parentId) && !hasAttachmentId), "第一级的公司必须上传公司logo");

        DomainInitUtil.initUpdateDomain(info);
        companyMapper.updateByPrimaryKeySelective(info);


        OrgInfo record=new OrgInfo();
        record.setType("0");
        record.setOrgId(id);
        record.setIdPath(id);
        BeanUtils.copyProperties(info, record);
        if(StringUtils.isNotEmpty(parentId)){
            Map map = orgInfoMapper.findOrg(parentId);
            record.setIdPath((String)map.get("ID_PATH") + "#" + record.getIdPath());
        }
        orgInfoMapper.updateByPrimaryKeySelective(record);

        if(hasAttachmentId) {//有附件
            Attachment atta = attachmentService.queryAttachmentByCustomOne(id, COMPANY_LOGO_TYPE);
            Attachment newAtta = attachmentMapper.selectByPrimaryKey(attachmentId);
            if(atta != null && newAtta != null) {
                String md5 = atta.getUniqueIdentifies();
                if(!atta.getId().equals(attachmentId)) {
                    updateChildCompanyLogo(id, newAtta, md5);
                }
                atta.setDeleted((short) 1);
                attachmentMapper.updateByPrimaryKeySelective(atta);
                newAtta.setBusinessId(id);
                attachmentMapper.updateByPrimaryKeySelective(newAtta);
            }
        }
	}

    /**
     * 更新子公司logo
     * @param companyId
     * @param newAtta
     * @param md5
     */
    private void updateChildCompanyLogo(String companyId, Attachment newAtta, String md5){
        CompanyVO comVO = new CompanyVO();
        comVO.setParentId(companyId);
        Attachment atta2;
        CompanyDTO dto;
        List<CompanyDTO> companyDTOList = companyMapper.queryAll(comVO);
        for(int i = 0, len = companyDTOList.size(); i < len; i++) {
            dto = companyDTOList.get(i);
            companyId = dto.getId();
            atta2 = attachmentService.queryAttachmentByCustomOne(companyId, COMPANY_LOGO_TYPE);
            if(atta2 != null && atta2.getUniqueIdentifies().equals(md5)) {
                BeanUtils.copyProperties(newAtta, atta2 ,"id", "businessId");
                attachmentMapper.updateByPrimaryKeySelective(atta2);
                updateChildCompanyLogo(companyId, newAtta, md5);
            }
        }
    }

    /**
     * 根据条件查询公司信息
     * @param companyVO
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-11-09
     */
	@Override
    public List<CompanyDTO> queryAll(CompanyVO companyVO) {
        return companyMapper.queryAll(companyVO);
    }

    @Override
    @Cacheable(value = "tempStoreData", key = "#root.targetClass.toString() + 'queryCacheAll'")
    public List<CompanyDTO> queryCacheAll() {
        return companyMapper.queryAll(new CompanyVO());
    }

    @Override
    public CompanyLogoVO getUserCompanyLogo() {
        CompanyLogoVO companyLogoVO = new CompanyLogoVO();
        UserSessionVO userSessionVO = SessionCacheSupport.getSessionVO();
        UserVO userVO =  userSessionVO.getUserDetailInfo();
        if(userVO == null) {
            return companyLogoVO;
        }
		String companyId = userVO.getCompanyId();
		if(StringUtils.isEmpty(companyId)){
			return companyLogoVO;
		}
        Attachment attachment = attachmentService.queryAttachmentByCustomOne(companyId, COMPANY_LOGO_TYPE);
        String path = (attachment == null ? "" : Globals.getProperties("upload_file_dir") + "/" + attachment.getPath());
        return companyLogoVO.setId(companyId).setLogoPath(path).setName(userVO.getCompany());
    }

    public CompanyLogoVO getUserTopCompanyLogo(String userName){
        List<CustomUser> userList = userService.getUser(userName);
        Company company = null;
        String companyId = null ;
        if(userList.size() > 0)
        {
            companyId = userList.get(0).getCompanyId();
        }

        while (!StringUtils.isEmpty(companyId))
        {
            Company t = companyMapper.selectByPrimaryKey(companyId);
            if(t != null && StringUtils.isEmpty(t.getParentId()))
            {
                company = t;
                companyId = company.getParentId();
            }
        }
        CompanyLogoVO companyLogoVO = new CompanyLogoVO();
        if(company == null )
        {
            companyLogoVO.setName("");
            return companyLogoVO;
        }



        Attachment attachment = attachmentService.queryAttachmentByCustomOne(companyId, COMPANY_LOGO_TYPE);
        String path = (attachment == null ? "" : Globals.getProperties("upload_file_dir") + "/" + attachment.getPath());
        return companyLogoVO.setId(companyId).setLogoPath(path).setName(company.getName());
    }
}
